package com.stylefeng.guns.modular.flagglory.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.persistence.model.Question;
import com.stylefeng.guns.common.persistence.model.QuestionCategory;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.flagglory.service.IQuestionCategoryService;
import com.stylefeng.guns.modular.flagglory.warpper.QuestionCategoryWarpper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 题库分类控制器
 *
 * @author fengshuonan
 * @Date 2018-01-30 09:36:22
 */
@Controller
@RequestMapping("/questionCategory")
public class QuestionCategoryController extends BaseController {

    private String PREFIX = "/flagGlory/questionCategory/";

    @Autowired
    private IQuestionCategoryService questionCategoryService;

    /**
     * 跳转到题库分类首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "questionCategory.html";
    }

    /**
     * 跳转到添加题库分类
     */
    @RequestMapping("/questionCategory_add")
    public String questionCategoryAdd() {
        return PREFIX + "questionCategory_add.html";
    }

    /**
     * 跳转到修改题库分类
     */
    @RequestMapping("/questionCategory_update/{questionCategoryId}")
    public String questionCategoryUpdate(@PathVariable Integer questionCategoryId, Model model) {
        QuestionCategory questionCategory = questionCategoryService.selectById(questionCategoryId);
        model.addAttribute("item", questionCategory);
        QuestionCategory pQuestionCategory = questionCategoryService.selectById(questionCategory.getPid());
        if (null != pQuestionCategory) {
            model.addAttribute("pName", pQuestionCategory.getName());
        } else {
            model.addAttribute("pName", "顶级");
        }
        LogObjectHolder.me().set(questionCategory);
        return PREFIX + "questionCategory_edit.html";
    }

    /**
     * 获取题库分类列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        List<Map<String, Object>> questionCategories = questionCategoryService.selectMaps(null);
        return super.warpObject(new QuestionCategoryWarpper(questionCategories));
    }

    /**
     * 新增题库分类
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@Valid QuestionCategory questionCategory, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        Integer pid = questionCategory.getPid();
        QuestionCategory pCategory = questionCategory.selectById(pid);
        if (null != pCategory) {
            String pids = pCategory.getPids();
            if (StringUtils.isBlank(pids)) {
                questionCategory.setPids(pCategory.getId().toString());
            } else {
                questionCategory.setPids(pids + "_" + pCategory.getId().toString());
            }
        }else {
            questionCategory.setPids("");
        }
        questionCategoryService.insert(questionCategory);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除题库分类
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer questionCategoryId) throws Exception{
        EntityWrapper<QuestionCategory> questionCategoryEntityWrapper = new EntityWrapper<>();
        questionCategoryEntityWrapper.where("pid=" + questionCategoryId);
        int count = questionCategoryService.selectCount(questionCategoryEntityWrapper);
        if(count > 0){
            throw new Exception("当前分类下有未删除的子分类！");
        }
        questionCategoryService.deleteById(questionCategoryId);
        return SUCCESS_TIP;
    }

    /**
     * 修改题库分类
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@Valid QuestionCategory questionCategory, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        //判断是否是当前分类的子分类
        QuestionCategory pQuestionCategory = questionCategoryService.selectById(questionCategory.getPid());
        if (null != pQuestionCategory) {
            if (questionCategory.getId() == pQuestionCategory.getId()) {
                throw new Exception("父分类选择有误！");
            }
            String pPids = pQuestionCategory.getPids();
            String[] pidArray = pPids.split("_");
            for (String id : pidArray) {
                if (id.equals(questionCategory.getId().toString())) {
                    throw new Exception("父分类选择有误！");
                }
            }
            String pids = pQuestionCategory.getPids();
            if (StringUtils.isBlank(pids)) {
                questionCategory.setPids(pQuestionCategory.getId().toString());
            } else {
                questionCategory.setPids(pids + "_" + pQuestionCategory.getId().toString());
            }
        } else {
            questionCategory.setPids("");
        }
        questionCategoryService.updateById(questionCategory);
        return super.SUCCESS_TIP;
    }

    /**
     * 题库分类详情
     */
    @RequestMapping(value = "/detail/{questionCategoryId}")
    @ResponseBody
    public Object detail(@PathVariable("questionCategoryId") Integer questionCategoryId) {
        return questionCategoryService.selectById(questionCategoryId);
    }

    @RequestMapping(value = "/tree")
    @ResponseBody
    public Object tree() {
        return questionCategoryService.tree();
    }
}
